package com.ehotting.eaf.netty.loggers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ehotting.eaf.core.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 记录netty发送出去的消息
 */
public class NettyMsgSendLogger {

	private Logger logger;


	public final static String SERIAL = "_serial";
	public final static String START_TIME = "_startTime";
	public final static String COST_TIME = "costTime";
	public final static String REQUEST = "request";
	public final static String RESPONSE = "response";
	public final static String FUNCTION = "_action";
	public final static String EXCEPTION = "exception";

	public NettyMsgSendLogger(String loggerName){
		logger = LoggerFactory.getLogger(loggerName);
	}
	
	public  void info(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put(SERIAL, MDC.get(SERIAL));
		map.put(FUNCTION, MDC.get(FUNCTION));
		String timeString = MDC.get(START_TIME);
		
		if(timeString!=null){
			Long startTime = Long.parseLong(timeString);
			map.put(START_TIME, DateUtils.dateToString(new Date(startTime),"yyyy-MM-dd HH:mm:ss"));
			map.put(COST_TIME,String.valueOf(System.currentTimeMillis() - startTime));
		}
		
		String request = MDC.get(REQUEST);
		if(StringUtils.hasText(request)){
			JSONObject requestMap =  JSON.parseObject(request, JSONObject.class);
			map.put(REQUEST, requestMap);
		}
		
		String response = MDC.get(RESPONSE);
		if(StringUtils.hasText(response)){
			JSONObject responseMap =  JSON.parseObject(response, JSONObject.class);
			map.put(RESPONSE, responseMap);
		}
		
		String exception = MDC.get(EXCEPTION);
		if(StringUtils.hasText(exception)){
			map.put(EXCEPTION, exception);
		}
		
		logger.info(JSONObject.toJSONString(map));
		MDC.clear();
	}
	
	public  void info(String s,Object... args){
		logger.info(s,args);
	}
}
